import { constantRoutes } from '@/router'
import _ from 'lodash'
import { getMenus } from '@/api/menu'
/* Layout */
import Layout from '@/layout'

/**
 * 使用meta.role确定当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }// const tmp = route
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function routeFilter(routes) {
  const asynchronousRoutes = routes.filter(route => {
    const myComponent = resolve => require.ensure([], () => resolve(require('@/' + route.url + '.vue')))

    // 当children大于1 时 自动改为嵌套路由 实现多级菜单
    if (route.component === 'layout' || route.component === 'Layout') {
      route.component = Layout
    } else {
      route.component = myComponent
    }

    route.meta = { title: route.title, icon: route.icon, noCache: route.noCache === '1' }
    route.hidden = route.hidden === '1'

    if (route.children && route.children.length) {
      if (route.children.length >= 1) {
        route.alwaysShow = true
      }
      route.children = routeFilter(route.children)
    }
    return true
  })
  return asynchronousRoutes
}

export function RecursiveMenuArray(roots, menus) {
  roots.forEach(root => {
    root.children = _.remove(menus, function(menu) {
      return menu.pid === root.id
    })
    // 如果还有剩下的
    if (menus && menus.length > 0) {
      RecursiveMenuArray(root.children, menus)
    }
  })
}

/** 将数组列表转化为route数组
 *
 */
export function changeArrayToRoutes(routes) {
  // 1.取出pid为根目录的菜单
  const root_menu = _.remove(routes, (route) => {
    return route.pid === '0'
  })
  // 2.进行递归
  RecursiveMenuArray(root_menu, routes)

  // 3.将数组对象转化为route对象
  const asynchronousRoutes = routeFilter(root_menu)

  return asynchronousRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 从服务端获取菜单
      let accessedRoutes = getMenus().then(response => {
        const { data } = response
        accessedRoutes = data || []
        accessedRoutes = changeArrayToRoutes(accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
        resolve()
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
